#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main() {
  Mat src = imread("../images/9.jpeg");  // ("8.jpeg");
  if (src.empty()) {
    cout << "could not load image.." << endl;
    return -1;
  }
  namedWindow("opencv setup demo", CV_WINDOW_AUTOSIZE);
  imshow("opencv setup demo", src);

  Mat dst1, dst2;
  char dst_title1[] = "gray_src";

  Mat gray_src;
  cvtColor(src, gray_src, CV_BGR2GRAY);
  imshow(dst_title1, gray_src);
  Mat bin_img;
  adaptiveThreshold(~gray_src, bin_img, 255, ADAPTIVE_THRESH_MEAN_C,
                    THRESH_BINARY, 15, -2);  // 21--5
  imshow("binary img", bin_img);
  // 水平结构元素
  Mat hline =
      getStructuringElement(MORPH_RECT, Size(src.cols / 16, 1), Point(-1, -1));
  // 垂直结构元素
  Mat vline =
      getStructuringElement(MORPH_RECT, Size(1, src.rows / 16), Point(-1, -1));
  // 矩形结构元素
  Mat kenerl = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
  Mat hdst, vdst, temp1, temp2;

  /*
  // 提取水平线
  erode(bin_img, temp1, hline);
  dilate(temp1, hdst, hline);
  bitwise_not(hdst, hdst);
  blur(hdst, hdst, Size(3, 3), Point(-1, -1));
  imshow("Final result-h", hdst);
  */
  /*
  // 提取垂直线
  erode(bin_img, temp2, vline);
  dilate(temp2, vdst, vline);
  bitwise_not(vdst, vdst);
  blur(vdst, vdst, Size(3, 3), Point(-1, -1));
  imshow("Final result-v", vdst);
  */
  // 开操作进行提取
  /*
  Mat dst;
  morphologyEx(bin_img, dst, CV_MOP_OPEN, hline);
  bitwise_not(dst, dst);
  imshow("Final result-open-h", dst);
  */
  // 滤除干扰项
  erode(bin_img, temp1, kenerl);
  dilate(temp1, hdst, kenerl);
  bitwise_not(hdst, hdst);
  //blur(hdst, hdst, Size(3, 3), Point(-1, -1));
  imshow("Final result", hdst);
  waitKey(0);
  return 0;
}